<template>
  <a-form :form="form" @submit="handleSubmit">
    <a-form-item label="名称" v-bind="formItemLayout">
      <a-input
        :disabled="optType === 3"
        v-decorator="[
          'title',
          {
            initialValue: initInfo.title,
            rules: [
              { required: true, message: '必填项！' },
              {
                validator: $validate.validateLength,
                max: 20,
                min: 1
              }
            ]
          }
        ]"
      />
    </a-form-item>
    <a-form-item label="分类" v-bind="formItemLayout">
      <a-select
        :disabled="optType === 3"
        v-decorator="[
          'class_id',
          {
            initialValue: initInfo.class_id,
            rules: [{ required: true, message: '请选择分类！' }]
          }
        ]"
      >
        <a-select-option
          v-for="(item, key) in classInfo"
          :key="key"
          :value="item.id"
        >
          {{ item.title }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="类型" v-bind="formItemLayout">
      <a-select
        :disabled="optType === 3"
        mode="multiple"
        v-decorator="[
          'tags',
          {
            initialValue: initInfo.tags,
            rules: [{ required: true, message: '请选择类型！' }]
          }
        ]"
      >
        <a-select-option
          v-for="(item, key) in typeInfo"
          :key="key"
          :value="item.id"
        >
          {{ item.title }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="地区" v-bind="formItemLayout">
      <a-input
        :disabled="optType === 3"
        v-decorator="[
          'area',
          {
            initialValue: initInfo.area,
            rules: [{ required: true, message: '必填项！' }]
          }
        ]"
      />
    </a-form-item>
    <a-form-item label="片长" v-bind="formItemLayout">
      <a-input-number
        :disabled="optType === 3"
        v-decorator="['movie_time', { initialValue: initInfo.movie_time }]"
      />
      分钟
    </a-form-item>
    <a-form-item label="上映时间" v-bind="formItemLayout">
      <a-date-picker
        :showTime="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
        :disabled="optType === 3"
        v-decorator="[
          'release_time',
          {
            initialValue: initInfo.release_time
              ? moment(initInfo.release_time)
              : null
          }
        ]"
      />
    </a-form-item>
    <a-form-item
      label="封面图"
      v-bind="formItemLayout"
      help="建议图片宽高为：200px*286px"
    >
      <div class="clearfix">
        <a-upload
          :disabled="optType === 3"
          v-decorator="[
            'upload',
            {
              initialValue: initInfo.upload,
              valuePropName: 'fileList',
              getValueFromEvent: normFile,
              rules: [{ required: true, message: '请上传封面图' }]
            }
          ]"
          accept="image/*"
          listType="picture-card"
          name="file"
          :multiple="false"
          :showUploadList="false"
          :action="$api.upload"
          :data="postData"
          :beforeUpload="beforeUpload"
        >
          <img
            v-if="imageUrl"
            :src="$api.picPre + imageUrl"
            alt="avatar"
            style="width: 64px"
          />
          <div v-else>
            <a-icon :type="loading ? 'loading' : 'plus'" />
            <div class="ant-upload-text">上传封面图</div>
          </div>
        </a-upload>
      </div>
    </a-form-item>
    <a-form-item
      label="背景图"
      v-bind="formItemLayout"
      help="建议图片宽高为：375px*221px"
    >
      <div class="clearfix">
        <a-upload
          :disabled="optType === 3"
          v-decorator="[
            'background',
            {
              initialValue: initInfo.background,
              valuePropName: 'fileListBg',
              getValueFromEvent: normFileBg,
              rules: [{ required: true, message: '请上传背景图' }]
            }
          ]"
          accept="image/*"
          listType="picture-card"
          name="file"
          :multiple="false"
          :showUploadList="false"
          :action="$api.upload"
          :data="bgPostData"
          :beforeUpload="beforeUploadBg"
        >
          <img
            v-if="imageBgUrl"
            :src="$api.picPre + imageBgUrl"
            alt="avatar"
            style="width: 64px"
          />
          <div v-else>
            <a-icon :type="bgLoading ? 'bgLoading' : 'plus'" />
            <div class="ant-upload-text">上传背景图</div>
          </div>
        </a-upload>
      </div>
    </a-form-item>
    <a-form-item label="项目简介" v-bind="formItemLayout" required>
      <div class="edit_container">
        <!--  新增时输入 -->
        <quill-editor
          v-if="optType !== 3"
          v-model="content"
          ref="myQuillEditor"
          :options="editorOption1"
        >
        </quill-editor>
        <!-- 从数据库读取展示 -->
        <div v-else v-html="str" class="ql-editor">
          {{ str }}
        </div>
      </div>
    </a-form-item>
    <a-form-item label="宣发计划" v-bind="formItemLayout" required>
      <div class="edit_container">
        <editor
          ref="content"
          v-if="optType !== 3"
          :defaultValue="initInfo.advertisement"
        ></editor>
        <!-- 从数据库读取展示 -->
        <div v-else v-html="planStr" class="ql-editor">
          {{ planStr }}
        </div>
      </div>
    </a-form-item>
    <a-form-item label="是否推荐" v-bind="formItemLayout">
      <a-select
        v-decorator="[
          'is_recommend',
          {
            initialValue: initInfo.is_recommend,
            rules: [{ required: true, message: '必选项' }]
          }
        ]"
      >
        <a-select-option value="1">
          推荐
        </a-select-option>
        <a-select-option value="2">
          不推荐
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-row v-if="optType !== 3">
      <a-col :span="24" :style="{ textAlign: 'center' }">
        <a-button type="primary" html-type="submit">
          提交
        </a-button>
        <a-button :style="{ marginLeft: '8px' }" @click="handleReset">
          重置
        </a-button>
      </a-col>
    </a-row>
  </a-form>
</template>

<script>
import editor from "@/components/vueQuillEditor/index";
import { getToken } from "@/tool/qiniu";
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import moment from "moment";
export default {
  name: "add",
  components: {
    quillEditor,
    editor
  },
  data() {
    return {
      formLayout: "horizontal",
      form: this.$form.createForm(this),
      previewVisible: false,
      fileList: [],
      fileListBg: [],
      previewImage: "",
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 }
        }
      },
      classInfo: [],
      typeInfo: [],
      content: "",
      str: "",
      editorOption1: {
        theme: "snow",
        modules: {
          toolbar: [
            [{ size: ["small", false, "large", "huge"] }], // 字体大小
            ["bold", "italic", "underline", "strike"], //加粗，斜体，下划线，删除线
            [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
            [{ list: "ordered" }, { list: "bullet" }], //列表
            [{ indent: "-1" }, { indent: "+1" }], // 缩进
            [{ header: [1, 2, 3, 4, 5, 6, false] }], //几级标题
            [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
            [{ font: [] }], //字体
            [{ align: [] }] //对齐方式
          ]
        }
      },
      editorOption: {
        theme: "snow",
        modules: {
          toolbar: [
            [{ size: ["small", false, "large", "huge"] }], // 字体大小
            ["bold", "italic", "underline", "strike"], //加粗，斜体，下划线，删除线
            [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
            [{ list: "ordered" }, { list: "bullet" }], //列表
            [{ indent: "-1" }, { indent: "+1" }], // 缩进
            [{ header: [1, 2, 3, 4, 5, 6, false] }], //几级标题
            [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
            [{ font: [] }], //字体
            [{ align: [] }], //对齐方式
            ["image"] //上传图片、上传视频
          ]
        }
      },
      planStr: "",
      initInfo: {
        upload: [],
        background: []
      },
      postData: {
        token: ""
      },
      bgPostData: {
        token: ""
      },
      loading: false,
      bgLoading: false,
      imageUrl: "",
      imageBgUrl: "",
      optType: 1
    };
  },
  methods: {
    moment,
    handleSubmit(e) {
      e.preventDefault();
      let planContent = this.$refs.content.getContent();
      this.form.validateFields((err, values) => {
        if (!err) {
          if (this.content === "") {
            this.$notification.warning({
              message: "请填写项目简介！"
            });
          } else if (planContent === "") {
            this.$notification.warning({
              message: "请填写宣发计划！"
            });
          } else {
            let obj = JSON.parse(JSON.stringify(values));
            if (values.upload) {
              obj.pic = values.upload[0].response.key;
              delete obj.upload;
            }
            if (values.background) {
              obj.background_img = values.background[0].response.key;
            }
            obj.introduction = this.content;
            obj.advertisement = planContent;
            obj.tags = obj.tags.join(",");
            if (values.release_time) {
              obj.release_time = moment(values.release_time).format(
                "YYYY-MM-DD HH:mm:ss"
              );
            }
            let api = null;
            if (this.optType === 1) {
              api = this.$api.addProjectBaseInfo;
              obj.type = 1;
            } else if (this.optType === 2) {
              api = this.$api.editProjectBaseInfo;
              obj.id = this.$route.params.id;
              obj.type = 2;
            }
            this.$ajax
              .post(api, obj)
              .then(() => {
                this.$notification.success({
                  message: "操作项目基本参数成功"
                });
                if (this.optType === 1) {
                  this.$router.push({ name: "projectList" });
                }
              })
              .catch(err => {
                this.$notification.error({
                  message: err
                });
              });
          }
        }
      });
    },
    handlePreview(file) {
      this.previewImage = file.url || file.thumbUrl;
      this.previewVisible = true;
    },
    handleChange({ fileList }) {
      this.fileList = fileList;
    },
    change(info) {
      if (info.file.status !== "uploading") {
        this.$message.info(info.file, info.fileList);
      }
      if (info.file.status === "done") {
        this.$message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === "error") {
        this.$message.error(`${info.file.name} file upload failed.`);
      }
    },
    handleCancel() {
      this.form.resetFields();
      this.$emit("handleCancel");
    },
    handleReset() {
      this.form.resetFields();
    },
    beforeUpload(file) {
      let timestamp2 = new Date().getTime();
      let typeArr = file.name.split(".");
      let type = typeArr[typeArr.length - 1];
      let savekey = "project/" + timestamp2 + "." + type;
      this.postData.token = getToken(savekey);
      let _this = this;
      let imgWidth = "";
      let imgHight = "";
      const isSize = new Promise(function(resolve, reject) {
        let width = 200;
        let height = 286;
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          imgWidth = img.width;
          imgHight = img.height;
          let valid = img.width == width && img.height == height;
          valid ? resolve() : reject();
        };
        img.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          _this.$notification.error({
            message:
              "图片大小不符合标准,宽高为200px*286px。当前上传图片的宽高分别为：" +
              imgWidth +
              "px和" +
              imgHight +
              "px"
          });
          return Promise.reject();
        }
      );
      return isSize;
    },
    beforeUploadBg(file) {
      let timestamp2 = new Date().getTime();
      let typeArr = file.name.split(".");
      let type = typeArr[typeArr.length - 1];
      let savekey = "projectBg/" + timestamp2 + "." + type;
      this.bgPostData.token = getToken(savekey);
      let _this = this;
      let imgWidth = "";
      let imgHight = "";
      const isSize = new Promise(function(resolve, reject) {
        let width = 375;
        let height = 221;
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          imgWidth = img.width;
          imgHight = img.height;
          let valid = img.width == width && img.height == height;
          valid ? resolve() : reject();
        };
        img.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          _this.$notification.error({
            message:
              "图片大小不符合标准,宽高为375px*221px。当前上传图片的宽高分别为：" +
              imgWidth +
              "px和" +
              imgHight +
              "px"
          });
          return Promise.reject();
        }
      );
      return isSize;
    },
    normFile(e) {
      if (e.file.status === "uploading") {
        this.loading = true;
        return e && e.fileList;
      } else if (e.file.status === "done") {
        this.imageUrl = e.file.response.key;
        this.loading = false;
        if (e.fileList.length > 1) {
          e.fileList.splice(0, 1);
        }
      }
      return e && e.fileList;
    },
    normFileBg(e) {
      if (e.file.status === "uploading") {
        this.bgLoading = true;
        return e && e.fileList;
      } else if (e.file.status === "done") {
        this.imageBgUrl = e.file.response.key;
        this.bgLoading = false;
        if (e.fileList.length > 1) {
          e.fileList.splice(0, 1);
        }
      }
      return e && e.fileList;
    },
    getClassInfo() {
      this.$ajax
        .get(this.$api.getProjectClassList, {
          status: 1,
          page_size: 100,
          page: 1
        })
        .then(res => {
          this.classInfo = res.data;
        })
        .catch(err => {
          this.$notification.error({
            message: err
          });
        });
    },
    getTypeInfo() {
      this.$ajax
        .get(this.$api.getProjectTypeList, {
          status: 1,
          page_size: 100,
          page: 1
        })
        .then(res => {
          this.typeInfo = res.data;
        })
        .catch(err => {
          this.$notification.error({
            message: err
          });
        });
    },
    getInfo() {
      this.$ajax
        .get(this.$api.detailProjectBaseInfo, {
          id: this.$route.params.id
        })
        .then(res => {
          this.initInfo = res;
          this.initInfo.upload = [
            {
              uid: "1",
              status: "done",
              url: this.$api.picPre + res.pic,
              name: res.title,
              response: {
                key: res.pic
              }
            }
          ];
          this.initInfo.background = [
            {
              uid: "1",
              status: "done",
              url: this.$api.picPre + res.background_img,
              name: res.background_img,
              response: {
                key: res.background_img
              }
            }
          ];
          this.imageUrl = res.pic;
          this.imageBgUrl = res.background_img;
          this.content = this.initInfo.introduction;
          if (this.initInfo.release_time) {
            this.initInfo.release_time = new Date(
              parseInt(this.initInfo.release_time) * 1000
            );
          }
          this.planStr = this.initInfo.advertisement;
          this.str = this.initInfo.introduction;
        })
        .catch(err => {
          this.$notification.error({
            message: err
          });
        });
    }
  },
  created() {
    if (this.$route.name === "editProject") {
      this.optType = 2;
      this.getInfo();
    } else if (this.$route.name === "detailsProject") {
      this.optType = 3;
      this.getInfo();
    } else {
      this.optType = 1;
    }
    this.getClassInfo();
    this.getTypeInfo();
  }
};
</script>

<style scoped></style>
